package com.zhenhao.xsq.base;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;


import com.zhenhao.xsq.view.ProgressDialog;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;


/**
 * @author Yuan.Y.Q
 * @Date 2017/9/26.
 */

public abstract class BaseFragment extends Fragment {
    public ProgressDialog progressDialog;
    //Fragment的View加载完毕的标记
    public boolean isViewCreated;

    //Fragment对用户可见的标记
    public boolean isUIVisible;
    public boolean isDataLoaded; // 数据是否已请求

    protected abstract void setupFragmentComponent();

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isUIVisible = isVisibleToUser;
        lazyLoad();

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewCreated = true;
        lazyLoad();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupFragmentComponent();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        progressDialog = new ProgressDialog(activity);
//		progressDialog.setMyCancelListener(this);
    }

    protected abstract void initDataFromLocal();

    /**
     * 启动Activity
     *
     * @param <T>
     * @param clazz
     */
    protected <T> void startActivity(Class<T> clazz) {
        Intent intent = new Intent(getActivity(), clazz);
        try {
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(getActivity(), "敬请期待！" + clazz.getSimpleName() + "未注册！", Toast
                    .LENGTH_SHORT).show();
        }
    }

    /**
     * 启动Activity
     *
     * @param clazz
     */
    protected <T> void startActivity(Class<T> clazz, Bundle bundle) {
        Intent intent = new Intent(getActivity(), clazz);
        intent.putExtras(bundle);
        try {
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getActivity(), "敬请期待！" + clazz.getSimpleName() + "未注册！", Toast
                    .LENGTH_SHORT).show();
        }
    }

    private void lazyLoad() {
        if (isViewCreated && isUIVisible && !isDataLoaded) {
            initDataFromLocal();
            isDataLoaded = true;
        }

    }
}
